# -*- coding: utf-8 -*-

import os

from google.appengine.ext import webapp
from datetime import datetime
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.db import Key
from google.appengine.api import users
from django.utils import simplejson
from time import strftime
from django.utils import simplejson

from baseclass import BaseHandler
from model import Annotation


class AnnotationQuery(BaseHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            email = user.email()
        if self.request.get("email"):
            email = self.request.get("email")        
        try:
            query = db.Query(Annotation)
            if email:
                query.filter("uri =", self.request.get("uri").rstrip("#")).filter("email =", email)
            else:
                query.filter("uri =", self.request.get("uri").rstrip("#"))
            if self.request.get("tagid"):
                query.filter("tagid =", self.request.get("tagid"))
            query.order("-date")
            items = query.fetch(999)
            if items:
                rows = []
                for item in items:
                    html = """<div><p>%(content)s</p><p>by &nbsp; <a href="mailto:%(email)s">%(author)s</a> &nbsp; %(date)s</p></div>""" % {"content": item.content, "author": item.author, "date": strftime("%Y/%m/%d %H:%M:%S", item.date.timetuple()), "email": "anonymous"}
                    # rows += """{"tagid":"%(tagid)s","html":"%(html)s"},""" % {"tagid": item.tagid, "html": html}
                    row = {"tagid": item.tagid, "html": html, "email": item.email, "author": item.author}
                    rows.append(row)
                if self.request.get("tagid"):
                    # contains id, single refresh
                    json = """{'msg': 'ok', 'refresh': 'yes',
                           'items':%s}""" % simplejson.dumps(rows)                    
                else:
                    json = """{'msg': 'ok',
                           'items':%s}""" % simplejson.dumps(rows)
            else:
                if self.request.get("tagid"):
                    json = """{"msg": "Please add your comments...",
                                "refresh": "yes"}"""
                else:
                    json = """{"msg": "Please add your comments..."}"""
        except:
            json = """{"msg": "error"}"""
        if self.request.get("callback"): 
            callback = self.request.get("callback")
        else:
            callback = "reachlinParseJson"
        if self.request.get("infunction"):
            self.response.out.write("%(func)s(%(param)s)" % {"func":callback, "param":json})            
        else:
            self.response.out.write(json)                


class AnnotationPreCheck(BaseHandler):
    def get(self):
        try:
            query = db.Query(Annotation)
            query.filter("uri =", self.request.get("uri").rstrip("#")).filter("email =", "anonymous")
            items = query.fetch(300)
            if items:
		rows = []
		for item in items:
			row = {"tagid":item.tagid, "email":item.email, "author":item.author}
			rows.append(row)
		self.response.out.write("""{"msg":"ok", "items":%s}""" % simplejson.dumps(rows))
            else:
                self.response.out.write("""{"msg":"not found"}""")
        except:
            self.response.out.write("""{"msg":"error"}""")

         
class AnnotationList(BaseHandler):
    def get(self):
        try:
            query = db.Query(Annotation)
            query.filter("uri =", self.request.get("uri").rstrip("#")).filter("tagid =", self.request.get("tagid"))
            items = query.fetch(100)
            if items:
                template_values = {"items": items}
            else:
                template_values = {"items": []}
        except:
            template_values = {"msg": "error"}
        try:
		language = self.request.headers['Accept-Language'].split(",")[0]
	except:
		language = "en"
	template_values["tagid"] = self.request.get("tagid")
	template_values["uri"] = self.request.get("uri").rstrip("#")
        if language == "zh" or language == "zh-cn":
            self.outputTemplate(template_values, "annotation_management_view_zh.html")
        else:
            self.outputTemplate(template_values, "annotation_management_view_en.html")                
                        

class AnnotationManagement(BaseHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            email = user.email()
        else:
            email = "anonymous"
        query = db.Query(Annotation)        
        query.filter("email =", email)
        query.order("-date")
        items = query.fetch(100);
        language = self.request.headers['Accept-Language'].split(",")[0]
        #LANGUAGE_CODE = language
        #language = self.request.cookies['django_language'] 
        if email=="anonymous":      
            template_values = {"items":items,
                           "django_language": language,
                           "loginurl": users.create_login_url(self.request.url)}
        else:
            template_values = {"items":items,
                           "django_language": language,
                           "email":email,
                           "loginurl": users.create_logout_url(self.request.url)}            
        if language == "zh" or language == "zh-cn":
            self.outputTemplate(template_values, "annotation_management_view_zh.html")
        else:
            self.outputTemplate(template_values, "annotation_management_view_en.html")                
        
class AnnotationModify(BaseHandler):
    def get(self):
        user = users.get_current_user()
        uri = self.request.get("uri").rstrip("#")
        tagid = self.request.get("tagid")
        query = db.Query(Annotation)
        query.filter("uri =", uri).filter("tagid =", tagid)        
        if user:
            query.filter("email =", user.email())
            item = query.get()
            template_values = {"item": item,
                               "uri": uri,
                               "tagid": tagid,
                               "email": user.email(),
                               "author": user.nickname(),
                               "loginurl": users.create_logout_url(self.request.url)}
        else:
            query.filter("email =", "anonymous")
            item = query.get()
            template_values = {"item": item,
                               "uri": self.request.get("uri").rstrip("#"),
                               "tagid": self.request.get("tagid"),                               
                               "loginurl": users.create_login_url(self.request.url)}       
        try:
		language = self.request.headers['Accept-Language'].split(",")[0]
	except:
		language = "en"
        if language == "zh" or language == "zh-cn":
            self.outputTemplate(template_values, "annotation_modify_view_zh.html")
        else:
            self.outputTemplate(template_values, "annotation_modify_view_en.html")                

    
    def post(self):
        user = users.get_current_user()
        if user:
            email = user.email()
        else:
            email = "anonymous"
        try:
            query = db.Query(Annotation)
            query.filter("email =", email).filter("uri =", self.request.get("uri")).filter("tagid =", self.request.get("tagid"))
            annotation = query.get()
            if not annotation:
                annotation = Annotation()
                annotation.email = email
                annotation.uri = self.request.get("uri")
                annotation.tagid = self.request.get("tagid")
            annotation.author = self.request.get("author")
            annotation.content = self.request.get("content")[0:365]
            annotation.rating = int(self.request.get("rating"))            
            annotation.put()
            template_values = {"msg":_("OK")}
        except:
            template_values = {"msg":"error"}
            
        try:
		language = self.request.headers['Accept-Language'].split(",")[0]
	except:
		language = "en"
        if language == "zh" or language == "zh-cn":
            self.outputTemplate(template_values, "annotation_modify_view_zh.html")
        else:
            self.outputTemplate(template_values, "annotation_modify_view_en.html")                
        
class AnnotationMainPage(BaseHandler):
    def get(self):
        template_values = {"home":True}
        try:
		language = self.request.headers['Accept-Language'].split(",")[0]
	except:
		language = "en"
        if language == "zh" or language == "zh-cn":
            self.outputTemplate(template_values, "annotation_view_zh.html")
        else:
            self.outputTemplate(template_values, "annotation_view_en.html")                
        
        
application = webapp.WSGIApplication(
                                     [
				      ('/annotation/precheck', AnnotationPreCheck),
				      ('/annotation/management', AnnotationManagement),
                                      ('/annotation/modify', AnnotationModify),
                                      ('/annotation/list', AnnotationList),
                                      ('/annotation/query', AnnotationQuery),
                                      ('/annotation/main', AnnotationMainPage),
                                      ('/annotation/main/', AnnotationMainPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
    
